package com.ys.everydaynews.view

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText

class CodeEditText @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatEditText(context, attrs) {
    init {
        addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                var testContent=s.toString()
                val lenght=testContent.length
                if (lenght==2){
                    if (testContent.substring(1)==" "){
                       setText("")
                        isCursorVisible=false
                    }else{
                        testContent="${testContent.substring(0,1)}  ${testContent.substring(1)}"
                        setText(testContent)
                        setSelection(testContent.length)
                        isCursorVisible=true
                    }
                }else if(lenght==5){
                    if (testContent.substring(4)==" "){
                        testContent=testContent.substring(0,3)
                        setText(testContent)
                        setSelection(testContent.length)
                    }else{
                        testContent="${testContent.substring(0,4)}  ${testContent.substring(4)}"
                        setText(testContent)
                        setSelection(testContent.length)
                    }
                }else if (lenght==8){
                    if (testContent.substring(7)==" "){
                        testContent=testContent.substring(0,6)
                        setText(testContent)
                        setSelection(testContent.length)
                    }else{
                        testContent="${testContent.substring(0,7)}  ${testContent.substring(7)}"
                        setText(testContent)
                        setSelection(testContent.length)
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })
    }
}